package com.hrms.service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.hrms.domain.Employee;

/**
 * Servlet Filter implementation class RequestFilter
 *
 * @web.filter
 *   name="RequestFilter" 
 *
 * @web.filter-mapping
 *   url-pattern="/admin/*"
 *   
 */
public class RequestFilter implements Filter {

	private static final Logger log = Logger.getLogger(RequestFilter.class.getName());
	private static UserService userService = UserServiceFactory.getUserService();
	private static final List<String> allowedList = Arrays.asList( "test.jsp" );
    /**
     * Default constructor. 
     */
    public RequestFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	        if (userService.isUserLoggedIn()) {
	        	User user=userService.getCurrentUser();
	        	Employee emp = Employee.getByUserId(user.getEmail().toLowerCase());
	        	String logOutUrl = userService.createLogoutURL("/");
	        	String page = ((HttpServletRequest) request).getRequestURI();
	        	
	        	if(emp != null || allowedList.contains(page)){
	        		request.setAttribute(Employee.TYPE, emp);
	        		chain.doFilter(request, response);
	        	}else{
	        		request.setAttribute("msg", "Service is not activated for your account. <a href=\""+logOutUrl+"\">Log Out</a>");
	        		forward(request, response, "/WEB-INF/include/msg.jsp");
	        	}
	        } else {
	        	((HttpServletResponse) response).sendRedirect(userService.createLoginURL(((HttpServletRequest) request).getRequestURI()));
	        }	
	}
	
	private void forward(ServletRequest request, ServletResponse response,
			String page) throws ServletException, IOException {
		RequestDispatcher dp = request.getRequestDispatcher(page);		
		try {
			dp.forward(request, response);
		} catch (Exception e) {
			log.log(Level.SEVERE, "Servlet Forward Failure..", e);
			dp.forward(request, response);
		}
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
